<template>
  <!-- 角色 -->
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <div style="margin-bottom:15px;text-align:left">
          <a-button
              v-action:add
              type='primary'
              icon="plus"
              @click="addrole"
          >新增角色
          </a-button>
        </div>
      </div>
      <a-table
          :columns="columns"
          :data-source="datalist"
          bordered
          :rowKey='record=>record.id'
          :pagination="true"
      >
        <template
            slot="status"
            slot-scope="text,record"
        >
          <a-switch
              v-action:changeStatus
              :checked=buer[text]
              @change="offset(record)"
              checked-children="正常"
              un-checked-children="禁用"
          />
        </template>

        <template
            slot="type"
            slot-scope="text,record"
        >
          <span v-if="text==0">系统</span>
          <span v-if="text==1">公司</span>
        </template>
        <template
            slot="操作"
            slot-scope="text, record"
        >
          <!-- <a
            href="javascript:;"
            style="margin-left:20px"
            @click="allot(record)"
          >分配用户</a> -->
          <a
              v-action:assignMenu
              href="javascript:;"
              style="margin-left:20px"
              @click="allcaidan(record)"
          >分配菜单</a>
          <a
              v-action:authority
              href="javascript:;"
              style="margin-left:20px"
              @click="fenpeiquanxian(record)"
          >分配权限</a>
          <a
              v-action:edit
              href="javascript:;"
              style="margin-left:20px"
              @click="bianji(record)"
          >编辑</a>
          <a-popconfirm
              style="margin-left:20px"
              cancelText='取消'
              okText="确认"
              title="您确定要删除吗?"
              @confirm="onDelete(record)"
          >
            <a
                v-action:del
                href="javascript:;"
            >删除</a>
          </a-popconfirm>
        </template>
      </a-table>
      <!-- <a-pagination show-quick-jumper :defaultPageSize='1'  :current='yeshu' :total="totalnum" @change="onChange1" style=" margin-top:15px;text-align:right" /> -->

      <!-- 分配角色 -->
      <a-modal
          :title="usertitle"
          :visible="visible1"
          :confirm-loading="confirmLoading1"
          @ok="handleOk1"
          @cancel="handleCancel"
          :destroyOnClose='true'
          cancel-text="取消"
          ok-text="确定"
      >
        <a-form-model
            ref="fenpeiform"
            :model="fenpeiform"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
            @submit="handleOk1"
        >
          <a-form-model-item
              label="当前角色"
              prop="name"
              :rules="{ required: true, message: '请选择用户', trigger: 'change' }"
          >
            <a-input
                v-model="fenpeiform.name"
                :disabled='true'
            />
          </a-form-model-item>
          <a-form-model-item
              label="选择人员"
              v-if="usertitle=='分配用户'"
              prop="userIds"
              :rules="{ required: true, message: '请选择', trigger: 'change' }"
          >
            <a-select
                allowClears
                mode="multiple"
                placeholder="请选择"
                v-model="fenpeiform.userIds"
            >
              <a-select-option
                  v-for="item in user"
                  :key="item.id"
              >
                <span v-if="item.name">{{ item.name }}</span>
                <span v-else>{{ item.account }}</span>
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
              label="分配权限"
              v-if="usertitle=='分配权限'"
              prop="dataScope"
              :rules="{ required: true, message: '请选择', trigger: 'change' }"
          >
            <a-select
                v-model="fenpeiform.dataScope"
                placeholder="请输入权限范围"
            >
              <a-select-option
                  v-for="(item,i) in juese"
                  :key="i"
                  :value="item.id"
              >{{ item.name }}
              </a-select-option>

            </a-select>
          </a-form-model-item>
          <a-form-model-item
              label="分配菜单"
              v-if="usertitle=='分配菜单'"
              prop="detpIds"
              :rules="{ required: true, message: '请选择', trigger: 'change' }"
          >
            <!--   showLine -->
            <a-tree
                defaultExpandAll
                v-model="fenpeiform.detpIds"
                checkable
                :replaceFields='replaceFields'
                :tree-data="caidan"
                checkStrictly
            />
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <!-- 新增 -->
      <a-modal
          :title="usertitle"
          :visible="visible"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
          @cancel="handleCancel"
          :destroyOnClose='true'
          cancel-text="取消"
          ok-text="确定"
      >
        <a-form-model
            ref="form"
            :model="form"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
            @submit="handleOk"
        >
          <a-form-model-item
              label="角色名称"
              prop="name"
              :rules="{ required: true, message: '请输入角色名称', trigger: 'blur' }"
          >
            <a-input
                allowClear
                placeholder="请输入角色名称"
                v-model="form.name"
            />
          </a-form-model-item>
          <a-form-model-item
              label="跳转路径"
              prop="webUrl"
              :rules="{ required: false, message: '请输入跳转路径', trigger: 'blur' }"
          >
            <a-input
                allowClear
                placeholder="请输入跳转路径"
                v-model="form.webUrl"
            />
          </a-form-model-item>
          <a-form-model-item
              label="跳转路径权重"
              prop=" weight"
              :rules="{ required: false, message: '请输入跳转路径权重', trigger: 'blur' }"
          >
            <a-input-number
                style="width: 100%"
                allowClear
                placeholder="请输入跳转路径权重"
                v-model="form.weight"
            />
          </a-form-model-item>
          <a-form-model-item
              label="权限范围"
              prop="dataScope"
              :rules="{ required: true, message: '请输入权限范围', trigger: 'blur' }"
          >
            <a-select
                v-model="form.dataScope"
                placeholder="请输入权限范围"
            >
              <a-select-option
                  v-for="(item,i) in juese"
                  :key="i"
                  :value="item.id"
              >{{ item.name }}
              </a-select-option>

            </a-select>
          </a-form-model-item>
          <a-form-model-item
              label="角色状态"
              prop="status"
              :rules="{ required: true, message: '请选择角色状态', trigger: 'blur' }"
          >
            <a-select
                v-model="form.status"
                placeholder="请选择角色状态"
            >
              <a-select-option
                  v-for="(item,i) in statusarr"
                  :key="i"
                  :value="item.id"
              >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
              label="类型"
              prop="type"
              :rules="{ required: true, message: '请选择类型', trigger: 'blur' }"
          >
            <a-select
                v-model="form.type"
                placeholder="请选择类型"
            >
              <a-select-option :value="0">系统</a-select-option>
              <a-select-option :value="1">公司</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
              label="角色排序"
              prop="orderNum"
              :rules="{ required: true, message: '请输入角色排序', trigger: 'blur' }"
          >
            <a-input-number
                placeholder="请输入角色排序"
                v-model="form.orderNum"
                style="width:100%"
                @change="onChange"
            />
          </a-form-model-item>
          <a-form-model-item
              label="备注"
              prop="remark"
              :rules="{ required: false, message: '请输入 ', trigger: 'blur' }"
          >
            <a-input
                placeholder="请输入"
                v-model="form.remark"
                style="width:100%"
            />
          </a-form-model-item>

        </a-form-model>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>
<script>
import {
  getlist,
  add,
  editstatus,
  deleterole,
  getuserlist,
  shuju,
  caidan,
  getcaidan,
  quanxian,
  juesecaidan,
  jueseyonghu,
  getusertree,
} from "@/api/rolement";

import {} from "@/api/sysRole";

import {getTreeData, getchild, urls, getTreeDatakey} from "@/utils/util";
import {forEach} from "store/storages/all";
import {TreeSelect} from "ant-design-vue";

const SHOW_PARENT = TreeSelect.SHOW_CHILD;

const columns = [
  {
    title: "排序",
    dataIndex: "orderNum",
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    align: "center",
  },
  {
    title: "角色名称",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "类型",
    dataIndex: "type",
    align: "center",
    scopedSlots: {customRender: "type"},
  },
  {
    title: "备注",
    dataIndex: "remark",
    align: "center",
    scopedSlots: {customRender: "remark"},
  },

  {
    title: "状态",
    dataIndex: "status",
    width:120,
    align: "center",
    scopedSlots: {customRender: "status"},
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: {customRender: "操作"},
    align: "center",
  },
];
export default {
  data() {
    return {
      SHOW_PARENT,
      replaceFields1: {
        children: "childList",
        title: "name",
        key: "key",
        value: "key",
      },
      replaceFields: {
        children: "childList",
        title: "name",
        key: "id",
        value: "id",
      },
      // form: this.$form.createForm(this, { name: "coordinated" }),
      form: {
        name: "",
        dataScope: "",
        status: null,
        orderNum: null,
      },
      // fenpeiform: this.$form.createForm(this, { name: "coordinated1",detpIds:[], }),
      fenpeiform: {
        name: "",
        userIds: [],
        dataScope: [],
        detpIds: [],
      },
      fenpei: "",
      columns,
      datalist: [],
      totalnum: 0,
      yeshu: 1,
      yingjilist: ["正常", "禁用"],
      usertitle: "",
      confirmLoading: false,
      visible: false,
      confirmLoading1: false,
      visible1: false,
      statusarr: [
        {id: 0, name: "正常"},
        {id: 1, name: "禁用"},
      ],
      buer: [true, false],
      juese: [
        {id: 0, name: "所有"},
        {id: 1, name: "本公司及下级"},
        {id: 2, name: "本公司"},
        {id: 3, name: "本部门及下级"},
        {id: 4, name: "本部门"},
      ],
      id: "",

      user: [],
      caidan: [],
      userarr: [],
    };
  },
  mounted() {
    this.getlist(1);
    this.yonghulist();
  },
  methods: {
    //从树里选择队员
    selecttree(value, label, extra) {
      console.log(value);

      let arr = [];
      let ids = [];
      this.child = [];
      //数据重组
      if (value.length != 0) {
      }
    },
    //获取人员树

    async getlist(val) {
      let response = await getlist({pageNo: val, pageSize: 10});
      if (response.code == 0) {
        this.datalist = response.data.records;
        this.totalnum = response.data.pages;
      }
    },
    onChange1(pageNumber) {
      this.yeshu = pageNumber;
      this.getlist(this.yeshu);
    },
    selectusertree(value, label, extra) {
      console.log("人员", value, label, extra);
      this.userarr = [];
      let userid = [];
      if (value.length != 0) {
        value.forEach((item) => {
          userid.push(item.value);
        });
        this.userarr = getTreeData(userid, this.treeData);
      }
      console.log(this.userarr);
    },
    onChange(val) {
      console.log(val);
    },
    //改变状态
    async offset(val) {
      console.log(val);
      let m;
      if (val.status) {
        m = 0;
      } else {
        m = 1;
      }
      let response = await editstatus({id: val.id, status: m});
      if (response.code == 0) {
        this.yeshu = 1;
        this.getlist(1);
      }
    },
    //新增
    addrole() {
      this.usertitle = "新增角色";
      this.visible = true;
      this.id = "";
    },
    //分配菜单
    async allcaidan(val) {
      console.log(val);
      this.usertitle = "分配菜单";
      this.fenpei = val;
      this.fenpeiform.name = val.name;
      await this.getcaidanliebiao();
      let response = await juesecaidan({id: val.id});
      if (response.code == 0) {
        this.visible1 = true;
        let data = [];
        if (response.data.length != 0) {
          response.data.forEach((item) => {
            data.push(item.id);
          });
          // console.log("菜单", data);
          this.fenpeiform.detpIds = data;
        } else {
          this.fenpeiform.detpIds = [];
        }
      }
    },

    //获取菜单列表
    async getcaidanliebiao() {
      let response = await getcaidan();
      console.log(response);
      if (response.code == 0) {
        this.caidan = response.data;
      }
    },
    //分配数据权限
    fenpeiquanxian(val) {
      console.log(val);
      this.usertitle = "分配权限";
      this.fenpei = val;
      this.visible1 = true;
      this.fenpeiform.dataScope = val.dataScope;
    },
    //分配用户
    async allot(val) {
      this.usertitle = "分配用户";
      this.fenpei = val;
      console.log("分配用户--", val);
      let response = await jueseyonghu({id: val.id});
      if (response.code == 0) {
        let data = [];
        response.data.forEach((item) => {
          data.push(item.id);
        });
        console.log(data);
        console.log("user", this.user);
        // let datas = getTreeData(data, this.user);
        // let newobj = {};
        // //对象去重
        // datas = datas.reduce((preVal, curVal) => {
        //   newobj[curVal.id]
        //     ? ""
        //     : (newobj[curVal.id] = preVal.push(curVal));
        //   return preVal;
        // }, []);
        // data = [];
        // datas.forEach((item) => {
        //   data.push(item.key);
        // });
        this.visible1 = true;

        console.log(data);

        this.fenpeiform.userIds = data;
      }
    },
    //获取用户列表
    async yonghulist() {
      let response = await getuserlist();
      if (response.code == 0) {
        // this.user = response.data;
        this.user = response.data.records;
      }
    },
    //编辑
    bianji(val) {
      console.log(val);
      this.usertitle = "编辑角色";
      this.visible = true;
      this.id = val.id;
      this.form = {
        name: val.name,
        dataScope: val.dataScope,
        status: val.status,
        orderNum: val.orderNum,
        remark: val.remark,
        type: val.type,
        webUrl: val.webUrl,
        weight: val.weight,
      };
    },
    //删除
    async onDelete(val) {
      let response = await deleterole({id: val.id});
      if (response.code == 0) {
        this.$notification.success({
          message: "成功",
          description: `删除成功`,
        });
        this.yeshu = 1;
        this.getlist(1);
      }
    },
    handleOk(e) {
      e.preventDefault();
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          let response = await add({...this.form, id: this.id});
          if (response.code == 0) {
            console.log(response);
            this.$message.success(response.msg)
            this.yeshu = 1;
            this.getlist(1);
            this.visible = false;
          }
        }
      });
    },
    handleOk1(e) {
      this.$refs["fenpeiform"].validate(async (valid) => {
        // this.fenpeiform.validateFields((err, values) => {
        if (valid) {
          this.confirmLoading1 = true;
          let data;
          if (this.usertitle == "分配用户") {
            data = {
              userIds: this.fenpeiform.userIds.join(","),
              id: this.fenpei.id,
            };
            let response = await shuju(data);
            if (response.code == 0) {
              this.$message.success(response.msg)
              this.yeshu = 1;
              this.getlist(1);
              this.visible1 = false;
            }
            this.confirmLoading1 = false;
          } else if (this.usertitle == "分配菜单") {
            // let arr = [];
            // this.fenpeiform.detpIds.forEach((item) => {
            //   arr.push(item.value);
            // });
            console.log(
                "this.fenpeiform.detpIds111==",
                this.fenpeiform.detpIds
            );
            console.log(
                "this.fenpeiform.detpIds",
                this.fenpeiform.detpIds.checked
            );
            if (this.fenpeiform.detpIds.checked != undefined) {
              data = {
                menuIds: this.fenpeiform.detpIds.checked.join(","),
                id: this.fenpei.id,
              };
            } else {
              data = {
                menuIds: this.fenpeiform.detpIds.join(","),
                id: this.fenpei.id,
              };
            }

            let response = await caidan(data);
            if (response.code == 0) {
              console.log(response);
              this.yeshu = 1;
              this.getlist(1);
              this.visible1 = false;
              this.$message.success(response.msg)
            }
            this.confirmLoading1 = false;
          } else if (this.usertitle == "分配权限") {
            let response = await quanxian({
              id: this.fenpei.id,
              ...this.fenpeiform,
            });
            if (response.code == 0) {
              // console.log(response);
              this.yeshu = 1;
              this.getlist(1);
              this.visible1 = false;
              this.confirmLoading1 = false;
              this.$message.success(response.msg)
            }
            this.confirmLoading1 = false;
          }
        }
      });
    },
    //取消弹窗
    handleCancel(e) {
      this.form = {
        id: "",
        name: "",
        dataScope: "",
        status: null,
        orderNum: null,
      };
      this.fenpeiform = {
        id: "",
        name: "",
        userIds: [],
        dataScope: [],
        detpIds: [],
      };
      this.visible = false;
      this.confirmLoading = false;
      this.visible1 = false;
      this.confirmLoading1 = false;
    },
  },
};
</script>

<style scoped>
.structure_cent {
  background: #fff;
  border: 1px solid #ccc;
}

.structure_cent_title {
  width: 100%;
  font-size: 16px;
  color: #333;
  background: #f6f6f6;
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  border-bottom: 1px solid #ccc;
}

.structure_cent_title span {
  border-left: 4px solid #0086ff;
  padding-left: 15px;
}

.structure_cent_b {
  max-width: 1200px;
  margin: auto;
  /* padding-top: 60px;
  padding-bottom: 60px; */
  display: flex;
  justify-content: space-between;
}

.structure_cent_b_left {
  width: 300px;
  border: 1px solid #ccc;
}

.structure_cent_b_right {
  width: 800px;
  margin-left: 20px;
}

.structure_cent_b_title {
  margin-bottom: 30px;
}

.addbtn_f {
  width: 400px;
  display: flex;
  justify-content: space-between;
}

.addbtn_f div {
  width: 100px;
  height: 35px;
  border: 1px solid #ccc;
  text-align: center;
  line-height: 35px;
  font-size: 13px;
  color: #333;
  cursor: pointer;
  background: #f2f2f2;
}

.addbtn_f div:hover {
  background: #0086ff;
  color: #fff;
}
</style>